package hierarchy

import (
	"database/sql"
	"encoding/json"
	"errors"
	"gitcode.com/G-YT/ANN/server/global"
	"gitcode.com/G-YT/ANN/server/model/common/request"
	"gitcode.com/G-YT/ANN/server/model/hierarchy"
	hierarchyReq "gitcode.com/G-YT/ANN/server/model/hierarchy/request"
	"gitcode.com/G-YT/ANN/server/model/hierarchy/response"
	public2 "gitcode.com/G-YT/ANN/server/model/public"
	"gitcode.com/G-YT/ANN/server/service/public"
	"gorm.io/gorm"
)

type CommentService struct {
}

var messageService = new(public.MessageService)

// CreateComment 创建Comment记录
// Author [piexlmax](https://github.com/piexlmax)
func (commentService *CommentService) CreateComment(comment *hierarchy.Comment) (err error) {
	table := ""
	var num sql.NullInt64
	switch comment.RootType {
	case "audio":
		table = "fd_article_audio"
	case "video":
		table = "fd_article_video"
	case "graphic":
		table = "fd_article_graphic"
	}
	if table != "" {
		err = global.GVA_DB.Table(table).Select("comment_num").Where("id = ?", comment.RootId).Pluck("comment_num", &num).Update("comment_num", num.Int64+1).Error
		if err != nil {
			return err
		}
	}

	var merr error
	var msg public2.Message
	var tb []byte
	var ce error

	err = global.GVA_DB.Create(comment).Error
	if err != nil {
		return err
	}
	if comment.CommentId == nil || *comment.CommentId == 0 {
		return nil
	}
	ce = global.GVA_DB.Preload("CreatedUser").Preload("TargetComment").Preload("TargetComment.CreatedUser").First(&comment, "comment_id = ?", comment.CommentId).Error
	if ce != nil {
		return ce
	}

	if comment.TargetComment == nil || comment.TargetComment.CreatedUser == nil || comment.CreatedUser == nil {
		return errors.New("未發現消息目標")
	}

	tb, err = json.Marshal(map[string]interface{}{
		"root_id":   comment.RootId,
		"root_type": comment.RootType,
		"user_name": comment.CreatedUser.Name,
		"avatar":    comment.CreatedUser.Avatar,
		"info":      comment.CreatedUser.Name + "回覆了您的評論",
	})

	msg = public2.Message{
		To:   comment.TargetComment.CreatedUser.Phone,
		Info: tb,
		Type: "comment",
	}
	merr = messageService.CreateMessage(&msg)
	if merr != nil {
		return merr
	}
	return err
}

// DeleteComment 删除Comment记录
// Author [piexlmax](https://github.com/piexlmax)
func (commentService *CommentService) DeleteComment(comment hierarchy.Comment) (err error) {
	err = global.GVA_DB.Delete(&comment).Error
	return err
}

// DeleteCommentByIds 批量删除Comment记录
// Author [piexlmax](https://github.com/piexlmax)
func (commentService *CommentService) DeleteCommentByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]hierarchy.Comment{}, "id in ?", ids.Ids).Error
	return err
}

// UpdateComment 更新Comment记录
// Author [piexlmax](https://github.com/piexlmax)
func (commentService *CommentService) UpdateComment(comment hierarchy.Comment) (err error) {
	err = global.GVA_DB.Save(&comment).Error
	return err
}

// GetComment 根据id获取Comment记录
// Author [piexlmax](https://github.com/piexlmax)
func (commentService *CommentService) GetComment(id uint) (comment hierarchy.Comment, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&comment).Error
	return
}

// GetCommentInfoList 分页获取Comment记录
// Author [piexlmax](https://github.com/piexlmax)
func (commentService *CommentService) GetCommentInfoList(info hierarchyReq.CommentSearch) (list any, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&hierarchy.Comment{}).Order("created_at desc")
	var comments []hierarchy.Comment

	db.Preload("TargetComment", func(db *gorm.DB) *gorm.DB {
		return db.Preload("CreatedUser")
	}).
		Preload("CreatedUser").
		Where("root_id = ? and root_type = ?", info.ConID, info.Type)

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Find(&comments).Error
	if info.Type != "comment" {
		resList := make([]response.CommentRes, 0)
		for i := range comments {
			var total int64
			global.GVA_DB.Model(&hierarchy.Comment{}).
				Where("root_id = ? and root_type = ?", comments[i].ID, "comment").Count(&total)

			resList = append(resList, response.CommentRes{
				ComAddTime: comments[i].CreatedAt.Format("2006-01-02"),
				ComId:      comments[i].ID,
				Comment:    comments[i].CommentInfo,
				CommentNum: total,
				MeId:       comments[i].CreatedBy,
				MeImg:      comments[i].CreatedUser.Avatar,
				MeNick:     comments[i].CreatedUser.Name,
				Pic:        comments[i].CreatedUser.Avatar,
			})
		}
		list = resList
	} else {
		resList := make([]response.CommentCRes, 0)
		for i := range comments {
			var RepId uint
			var ReMeNick string
			var ReplyId *uint
			if comments[i].TargetComment != nil {
				RepId = comments[i].TargetComment.ID
				ReMeNick = comments[i].TargetComment.CreatedUser.Name
				ReplyId = comments[i].TargetComment.CreatedBy
			}
			resList = append(resList, response.CommentCRes{
				RepId:      RepId,
				ReMeNick:   ReMeNick,
				ReplyId:    ReplyId,
				CreateTime: comments[i].CreatedAt.Format("2006-01-02"),
				ComId:      comments[i].ID,
				Comment:    comments[i].CommentInfo,
				MeId:       comments[i].CreatedBy,
				MeImg:      comments[i].CreatedUser.Avatar,
				MeNick:     comments[i].CreatedUser.Name,
			})
		}
		list = resList
	}
	return list, err
}
